<template>
  <a-drawer
    title="新增楼盘"
    :maskClosable="false"
    width=650
    placement="right"
    :closable="false"
    @close="onClose"
    :visible="userAddVisiable"
    style="height: calc(100% - 55px);overflow: auto;padding-bottom: 53px;">


    <a-form :form="form">
      <a-form-item label='楼盘名称' v-bind="formItemLayout">
        <a-input v-decorator="[
        'estateName',
        { rules: [{ required: true, message: '请输入楼盘名称!' }] }
        ]"/>
      </a-form-item>
      <a-form-item label='楼盘概述' v-bind="formItemLayout">
        <a-input v-decorator="[
        'estateContent',
        { rules: [{ required: true, message: '请输入楼盘概述!' }] }
        ]"/>
      </a-form-item>
      <a-form-item label='项目配套' v-bind="formItemLayout">
        <a-input v-decorator="[
        'matchs'
        ]"/>
      </a-form-item>
      <a-form-item label='楼盘类型' v-bind="formItemLayout">
        <a-select v-decorator="[
        'estateType'
        ]">
          <a-select-option value="0">热销楼盘</a-select-option>
          <a-select-option value="1">新盘预告</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label='地理位置' v-bind="formItemLayout">
        <a-input v-decorator="[
        'address'
        ]"/>
      </a-form-item>
      <a-form-item label='参考价格' v-bind="formItemLayout">
        <a-input v-decorator="[
        'referencePrice'
        ]"/>
      </a-form-item>
      <a-form-item label='开盘时间' v-bind="formItemLayout">
        <a-date-picker v-decorator="[
        'openTime'
        ]"/>
      </a-form-item>
      <a-form-item label='联系电话' v-bind="formItemLayout">
        <a-input v-decorator="[
        'contactNumber'
        ]"/>
      </a-form-item>
      <a-form-item label='主力户型' v-bind="formItemLayout">
        <a-input v-decorator="[
        'mainTyoe'
        ]"/>
      </a-form-item>
      <a-form-item label='物业类别' v-bind="formItemLayout">
        <a-select v-decorator="[
        'propertyType'
        ]">
          <a-select-option value="0">高层</a-select-option>
          <a-select-option value="1">住宅</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label='物业管理费' v-bind="formItemLayout">
        <a-input v-decorator="[
        'propertyPrice'
        ]"/>
      </a-form-item>
      <a-form-item label='物业公司' v-bind="formItemLayout">
        <a-input v-decorator="[
        'conpanyProperty'
        ]"/>
      </a-form-item>
      <a-form-item label='建筑类型' v-bind="formItemLayout">
        <a-select v-decorator="[
        'buildingType'
        ]">
          <a-select-option value="0">别墅 洋房</a-select-option>
          <a-select-option value="1">高层</a-select-option>
          <a-select-option value="2">平层住宅</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label='装修状态' v-bind="formItemLayout">
        <a-select v-decorator="[
        'decorationStatus'
        ]">
          <a-select-option value="0">精装</a-select-option>
          <a-select-option value="1">简装</a-select-option>
          <a-select-option value="2">轻奢</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label='项目状态' v-bind="formItemLayout">
        <a-select v-decorator="[
        'projectStatus'
        ]">
          <a-select-option value="0">在售</a-select-option>
          <a-select-option value="1">未开售</a-select-option>
          <a-select-option value="2">已售完</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label='户型区间' v-bind="formItemLayout">
        <a-input v-decorator="[
        'intervalUnit'
        ]"/>
      </a-form-item>
      <a-form-item label='产权年限' v-bind="formItemLayout">
        <a-input v-decorator="[
        'propertyRight'
        ]"/>
      </a-form-item>
      <a-form-item label='楼层状况' v-bind="formItemLayout">
        <a-input v-decorator="[
        'floor'
        ]"/>
      </a-form-item>
<!--      <a-form-item label='户型图' v-bind="formItemLayout">-->
<!--        <a-upload-->
<!--          name="avatar"-->
<!--          list-type="picture-card"-->
<!--          class="avatar-uploader"-->
<!--          :show-upload-list="false"-->
<!--          action="http://localhost:9527/web/fileUpload"-->
<!--          @change="imgHandleChange1"-->
<!--          :before-upload="beforeUpload"-->
<!--        >-->
<!--          <img v-if="img.imgUrl1" :src="img.imgUrl1" alt="avatar" style="width: 200px;height: 200px;"/>-->
<!--          <div v-else>-->
<!--            <a-icon :type="loadingImg ? 'loading' : 'plus'" />-->
<!--            <div class="ant-upload-text">-->
<!--              Upload-->
<!--            </div>-->
<!--          </div>-->
<!--        </a-upload>-->
<!--      </a-form-item>-->
      <a-form-item label='样板房图片' v-bind="formItemLayout">
        <a-upload
          name="avatar"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          action="http://localhost:9527/web/fileUpload"
          @change="imgHandleChange2"
          :before-upload="beforeUpload"
        >
          <img v-if="img.imgUrl2" :src="img.imgUrl2" alt="avatar" style="width: 200px;height: 200px;"/>
          <div v-else>
            <a-icon :type="loadingImg ? 'loading' : 'plus'" />
            <div class="ant-upload-text">
              Upload
            </div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label='园林景观' v-bind="formItemLayout">
        <a-upload
          name="avatar"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          action="http://localhost:9527/web/fileUpload"
          @change="imgHandleChange3"
          :before-upload="beforeUpload"
        >
          <img v-if="img.imgUrl3" :src="img.imgUrl3" alt="avatar" style="width: 200px;height: 200px;"/>
          <div v-else>
            <a-icon :type="loadingImg ? 'loading' : 'plus'" />
            <div class="ant-upload-text">
              Upload
            </div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label='地址' v-bind="formItemLayout">
        <a-input style="width: 70%" v-decorator="[
        'address'
        ]"/>
        <a-button type="primary" style="width: 30%" @click="showChildrenDrawer">
          选择地址
        </a-button>
      </a-form-item>

    </a-form>

    <drawerMap :childrenDrawerShow="childrenDrawer" @handlerClosed="handlerClosed"></drawerMap>


    <div class="drawer-bootom-button">
      <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>
  </a-drawer>
</template>
<script>
  import drawerMap from '@/utils/map/searchmap/drawerMap'
  import baiduMap from '@/utils/map/baiduMap'
  import dayjs from 'dayjs'

  const formItemLayout = {
    labelCol: { span: 3 },
    wrapperCol: { span: 18 }
  }
  export default {
    name: 'UserAdd',
    props: {
      userAddVisiable: {
        default: false
      }
    },
    components: {
      drawerMap
    },
    data () {
      return {
        loadingImg: false,
        // 别怪我这样写 太鸡儿ex
        img: {
          imgUrl1: '',
          imgName1: '',
          imgUrl2: '',
          imgName2: '',
          imgUrl3: '',
          imgName3: '',
        },
        stayAddress: '',
        user: {
          accountCode: '',
          accountPwd: '',
          accountName: '',
          expireDate: '',
          accountStatus: '',
          defaultApp: ''
        },
        localPoint: '',
        dateFormat: 'YYYY/MM/DD',
        loading: false,
        childrenDrawer: false,
        roleData: [],
        deptTreeData: [],
        mockData: [],
        targetKeys: [],
        appInfoData: [],
        roleInfoData: [],
        roleKeys: [],
        menuInfoData: [],
        orgInfoData: [],
        accountInfo: [],
        menuKeys: [],
        formItemLayout,
        defaultPassword: '1234qwer',
        form: this.$form.createForm(this),
        validateStatus: '',
        help: ''
      }
    },
    mounted() {
      //this.getMock();
      //this.getAppInfo();
      //this.getRoleInfo();
      //this.getMenuInfo();
      //this.getOrgInfo();
      //this.getAccountInfo();
    },
    methods: {
      getBase64(img, callback) {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
      },
      imgHandleChange1(info) {
        if (info.file.status === 'uploading') {
          this.loadingImg = true;
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          this.getBase64(info.file.originFileObj, imageUrl => {
            this.img.imgUrl1 = imageUrl;
            this.img.imgName1 = info.file.response;
            this.loadingImg = false;
          });
        }
      },
      imgHandleChange2(info) {
        if (info.file.status === 'uploading') {
          this.loadingImg = true;
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          this.getBase64(info.file.originFileObj, imageUrl => {
            this.img.imgUrl2 = imageUrl;
            this.img.imgName2 = info.file.response;
            this.loadingImg = false;
          });
        }
      },
      imgHandleChange3(info) {
        if (info.file.status === 'uploading') {
          this.loadingImg = true;
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          this.getBase64(info.file.originFileObj, imageUrl => {
            this.img.imgUrl3 = imageUrl;
            this.img.imgName3 = info.file.response;
            this.loadingImg = false;
          });
        }
      },
      beforeUpload(file) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
          this.$message.error('You can only upload JPG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M;
      },
      handlerClosed(localPoint) {
        this.childrenDrawer = false
        if(localPoint !=null && localPoint != undefined) {
          this.localPoint = localPoint;
          let address = baiduMap.getAddress(localPoint);
          address.getLocation(localPoint, (rs) => {
            if(rs != null) {
              if(rs.address != undefined && rs.address.length != 0) {
                this.stayAddress = rs.address;
              }
              if(rs.surroundingPois != undefined) {
                if(rs.surroundingPois.address != undefined && rs.surroundingPois.address.length != 0) {
                  this.stayAddress = rs.surroundingPois.address;
                }
              }

              this.form.getFieldDecorator("address")
              let obj = {}
              obj["address"] = this.stayAddress
              this.form.setFieldsValue(obj)

            }
          });
        }
      },
      showChildrenDrawer() {
        this.childrenDrawer = true;
      },
      reset () {
        this.loading = false
        this.form.resetFields()
      },
      onClose () {
        this.reset()
        this.$emit('close')
      },
      handleSubmit () {

        this.form.validateFields((err, values) => {
          if (!err) {
            this.loading = true
            values.point = JSON.stringify(this.localPoint)
            values.floorImg = this.img.imgName1
            values.sampleImg = this.img.imgName2
            values.scenicImg = this.img.imgName3
            values.openTime = dayjs(values.openTime).format('YYYY-MM-DD')
            this.$post('/cos/estate-info', {
              ...values
            }).then((r) => {
              this.reset()
              this.$emit('success')
            }).catch(() => {
              this.loading = false
            })

          }
        })
      },
      handleUserNameBlur () {
        let username = this.user.username.trim()
        if (username.length) {
          if (username.length > 10) {
            this.validateStatus = 'error'
            this.help = '用户名不能超过10个字符'
          } else if (username.length < 4) {
            this.validateStatus = 'error'
            this.help = '用户名不能少于4个字符'
          } else {
            this.validateStatus = 'validating'
            this.$get(`user/check/${username}`).then((r) => {
              if (r.data) {
                this.validateStatus = 'success'
                this.help = ''
              } else {
                this.validateStatus = 'error'
                this.help = '抱歉，该用户名已存在'
              }
            })
          }
        } else {
          this.validateStatus = 'error'
          this.help = '用户名不能为空'
        }
      },
      getMock() {
        const targetKeys = [];
        const mockData = [];
        for (let i = 0; i < 20; i++) {
          const data = {
            key: i.toString(),
            title: `content${i + 1}`,
            description: `description of content${i + 1}`,
            chosen: Math.random() * 2 > 1,
          };
          if (data.chosen) {
            targetKeys.push(data.key);
          }
          mockData.push(data);
        }
        this.mockData = mockData;
        this.targetKeys = targetKeys;
      },
      filterOption(inputValue, option) {
        return option.description.indexOf(inputValue) > -1;
      },
      handleChange(targetKeys, direction, moveKeys) {
        this.targetKeys = targetKeys;
      },
      handleChanges(targetKeys, direction, moveKeys) {
        this.roleKeys = targetKeys;
      },
      handleSearch(dir, value) {
        console.log('search:', dir, value);
      },
      onSelect(keys) {
        this.menuKeys = keys;
        console.log('Trigger Select', keys);
      },
      onCheck(checkedKeys, e) {
        console.log(JSON.stringify(checkedKeys));
      },
    },
    watch: {
      userAddVisiable () {
        if (this.userAddVisiable) {
          this.$get('role').then((r) => {
            this.roleData = r.data.rows
          })
          this.$get('dept').then((r) => {
            this.deptTreeData = r.data.rows.children
          })
        }
      }
    }
  }
</script>
